#pragma once

#include <iostream>
#include <functional>
#include <unistd.h>
#include <signal.h>
#include "Sock.hpp"

using func_t = std::function<void(int)>;

class HttpServer
{
public:
    HttpServer(const uint16_t& port, func_t func)
        : _port(port)
        , _func(func)
    {
        _listenSock = _sock.Socket();
        _sock.Bind(_listenSock, _port);
        _sock.Listen(_listenSock);
    }

    ~HttpServer()
    {
        if(_listenSock >= 0)
            close(_listenSock);
    }

    void Start()
    {
        signal(SIGCHLD, SIG_IGN);
        while(true)
        {
            std::string clientIP;
            uint16_t clientPort;
            int sockfd = _sock.Accept(_listenSock, &clientIP, &clientPort);
            if(sockfd < 0) continue;
            if(fork() == 0)
            {
                close(_listenSock);
                _func(sockfd);
                close(sockfd);
                exit(0);
            }
        }
    }

private:
    int _listenSock;
    uint16_t _port;
    Sock _sock;
    func_t _func;
};